<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Controller Content
 *
 * @author hoanguyen
 * @since Jan 2, 2014 - 9:25:21 AM
 */
class Content extends MY_Controller {

    function __construct() {
        parent::__construct();
        // load proto library
        $this->load_proto_libray();
        // load models
        $this->load->model('m_content');
        $this->load->model('m_backend_user');
    }

    function index() {
        
    }

    /*
     * Delete Content
     */

    function delete($content_id) {
        $this->load->library('zmq/ZmqMDClient', array());
        $mdClient = $this->config->item('mdClient');
        $verbose = $mdClient['verbose'];
        $brokerArray = $mdClient['brokerList'];
        $currentBroker = 0;

        $this->load->library('pb4php');
        $this->load->library('proto/proto');
        $uuid = uniqid();
        $contentType = $_GET['contentType'];
        if (isset($_GET['creator']) && $_GET['creator'] != '') {
            $type = $_GET['creator'];
        } else {
            $acxLogin = $this->config->item('acxLogin');
            $type = $acxLogin['default'];
        }

        try {
            /*
             * config value
             */
            $array_sessionKey = $array_uid = array();
            $array_sessionKey = $this->session->userdata('backendSessionKey');
            $array_uid = $this->session->userdata('backendUid');
            if (!isset($array_sessionKey[$type]) || $array_sessionKey[$type] == NULL) {
                $this->m_backend_user->backend_login($type);
                $array_sessionKey = $this->session->userdata('backendSessionKey');
                $array_uid = $this->session->userdata('backendUid');
            }
            $sessionKey = $array_sessionKey[$type];
            $uid = $array_uid[$type];
            $contentMessageRequest = $this->m_content->get_delete_content_request($uid, $uuid, $sessionKey, $content_id, $contentType);

            if ($contentMessageRequest != null) {
                $messageRequest = new zmsg();
                $messageRequest->body_set($contentMessageRequest);
                $this->mdpClient = new ZmqMDClient($brokerArray[$currentBroker], $verbose);
                $this->mdpClient->connect_to_broker();
                $contentMessageReply = $this->mdpClient->send("contents", $messageRequest);

                if (!$contentMessageReply) {
                    $currentBroker++;
                    if ($currentBroker > count($brokerArray))
                        $currentBroker = 0;
                    $this->mdpClient = new ZmqMDClient($brokerArray[$currentBroker], $verbose);
                    log_message('error', 'Noreply');  //Ghi log
                    _jsonout(FALSE, 'Noreply');
                } else {
                    $ItemCRUDReply = $this->m_content->get_message_reply($contentMessageReply);
                    if ($ItemCRUDReply->error_no() == ItemCRUDReply_ErrorNo::SUCCESS) {
                        switch ($contentType) {
                            case 'faq_topic':
                                redirect("FAQ/topic/index/$content_id");
                                break;
                            case 'faq_item':                                
                                break;
                            default :
                                redirect("$contentType/index/$content_id");
                        }
                    } else {
                        $data['error'] = $ItemCRUDReply->error_msg();
                        log_message('error', $ItemCRUDReply->error_msg()); //Ghi log trường hợp không thành công                            
                    }
                }
            } else {
                log_message('error', "ContentType not True"); //Ghi log trường hợp không thành công
            }
        } catch (MongoGridFSException $mge) {
            $array = array(ItemGetReply_ErrorType::FAIL_SYS, $mge->getMessage());
            $jsonEncode = json_encode($array);
            $jsonWriteLog = json_decode($jsonEncode, true);
            _jsonout(FALSE, $mge->getMessage()); //Return json array
            log_message('error', $jsonWriteLog);
        } catch (Exception $e) {
            $array = array(ItemGetReply_ErrorType::FAIL, $e->getMessage());
            $jsonEncode = json_encode($array);
            $jsonWriteLog = json_decode($jsonEncode, true);
            _jsonout(FALSE, $mge->getMessage()); //Return json array
            log_message('error', $jsonWriteLog);
        }
    }

    //Get list 
    public function ajax_get_list_content($offfset = 0, $number = 5) {
        $this->_plugins[] = "jquery_ui/js";
        $this->_plugins[] = "jquery_ui/css/Aristo";
        $this->load->library('pagination');

        $offset = $this->input->get('offset', 0);
        $params = array();
        $this->load->library('zmq/ZmqMDClient', $params);

        $mdClient = $this->config->item('mdClient');
        $verbose = $mdClient['verbose'];
        $brokerArray = $mdClient['brokerList'];
        $currentBroker = 0;

        $this->load->library('pb4php');
        $this->load->library('proto/proto');
        $uuid = uniqid();

        $acxLogin = $this->config->item('acxLogin');
        $type = $acxLogin['default'];
        $array_sessionKey = $array_uid = array();
        $array_sessionKey = $this->session->userdata('backendSessionKey');
        $array_uid = $this->session->userdata('backendUid');
        if (!isset($array_sessionKey[$type]) || $array_sessionKey[$type] == NULL) {
            $this->m_backend_user->backend_login($type);
            $array_sessionKey = $this->session->userdata('backendSessionKey');
            $array_uid = $this->session->userdata('backendUid');
        }

        try {
            $sessionKey = $array_sessionKey[$type];
            $uid = $array_uid[$type];

            $end_timestamp = $this->input->post('end_timestamp');
            $contentType = $this->input->post('contentType', NULL);            

            if ($end_timestamp == NULL || $end_timestamp == 0)
                $end_timestamp = time();
            $arr_tag_label = array($this->input->post('arr_tag_label'));

            $getListContentRequest = $this->m_content->get_list_content_request($uid, $uuid, $sessionKey, $number, $end_timestamp, $arr_tag_label, $contentType);            
            $messageRequest = new zmsg();
            $messageRequest->body_set($getListContentRequest);

            $this->mdpClient = new ZmqMDClient($brokerArray[$currentBroker], $verbose);

            $this->mdpClient->connect_to_broker();
            $getListContentReply = $this->mdpClient->send("contents", $messageRequest);             

            if (!$getListContentReply) {
                $currentBroker++;
                if ($currentBroker > count($brokerArray))
                    $currentBroker = 0;
                $this->mdpClient = new ZmqMDClient($brokerArray[$currentBroker], $verbose);
                log_message('error', 'Noreply');  //Ghi log
                _jsonout(FALSE, 'Noreply');
            } else {
                $arr_getListContent = $getListContent = $creator = array();
                $arr_getListContent = $this->m_content->get_list_content_reply($getListContentReply, $contentType);
                
                $getListContent = $arr_getListContent['contentItem'];
                $creator = $arr_getListContent['creator'];

                if ($getListContent != NULL) {
                    function cmp($a, $b) {
                        if ($a->update_timestamp() == $b->update_timestamp()) {
                            return 0;
                        }
                        return ($a->update_timestamp() < $b->update_timestamp()) ? 1 : -1;
                    }

                    usort($getListContent, "cmp");

                    $jsonArray = array();
                    $i = 0;

                    if ($contentType != 'faq_item') {
                        foreach ($getListContent as $key => $content) {
                            $jsonArray[$key] = array();                              
                            if($contentType != 'public_people'){
                                if ($content->thumb_picture_uri() != NULL) {
                                    $content->set_thumb_picture_uri(get_media_url($content->thumb_picture_uri()));
                                }
                            }else{
                                if ($content->profile_picture_uri() != NULL) {
                                    $content->set_profile_picture_uri(get_media_url($content->profile_picture_uri()));
                                }
                            }
                            
                            array_push($jsonArray[$key], $content->toJson());
                            if (isset($creator[$i])) {
                                array_push($jsonArray[$key], $creator[$i]->toJson());
                            }
                            $i++;
                        }
                    } else {
                        foreach ($getListContent as $key => $content) {
                            $jsonArray[$key] = array();
                            array_push($jsonArray[$key], $content->toJson());
                            if (isset($creator[$i])) {
                                array_push($jsonArray[$key], $creator[$i]->toJson());
                            }
                            $i++;
                        }
                    }                    
                    $arr_out = array();
                    $arr_out['content'] = $jsonArray;
                    $arr_out['total_items'] = $arr_getListContent['total_items'];

                    _jsonout(TRUE, 'success', json_encode($arr_out));
                } else {
                    _jsonout(TRUE, 'success', json_encode(array()));
                }
            }
        } catch (MongoGridFSException $mge) {
            $array = array(ItemGetReply_ErrorType::FAIL_SYS, $mge->getMessage());
            $jsonEncode = json_encode($array);
            $jsonWriteLog = json_decode($jsonUploadFile, true);
            _jsonout(FALSE, $mge->getMessage()); //Return json array
            log_message('error', $jsonWriteLog);
        } catch (Exception $e) {
            $array = array(ItemGetReply_ErrorType::FAIL, $e->getMessage());
            $jsonEncode = json_encode($array);
            $jsonWriteLog = json_decode($jsonUploadFile, true);
            _jsonout(FALSE, $mge->getMessage()); //Return json array
            log_message('error', $jsonWriteLog);
        }
    }

    /**
     * function search content
     * 
     * @param type $offfset
     * @param type $number
     */
    public function ajax_search_content($offfset = 0, $number = 5) {
        $this->_plugins[] = "jquery_ui/js";
        $this->_plugins[] = "jquery_ui/css/Aristo";
        $this->load->library('pagination');

        $offset = $this->input->get('offset', 0);
        $params = array();
        $this->load->library('zmq/ZmqMDClient', $params);

        $mdClient = $this->config->item('mdClient');
        $verbose = $mdClient['verbose'];
        $brokerArray = $mdClient['brokerList'];
        $currentBroker = 0;

        $this->load->library('pb4php');
        $this->load->library('proto/proto');
        $uuid = uniqid();

        $type = $_GET['type'];
        if ($type == '') {
            $acxLogin = $this->config->item('acxLogin');
            $type = $acxLogin['default'];
        }
        $this->get_backend_session_key($type);
        $keywords = $_GET['keywords'];

        $array_sessionKey = $array_uid = array();
        $array_sessionKey = $this->session->userdata('backendSessionKey');
        $array_uid = $this->session->userdata('backendUid');
        if (!isset($array_sessionKey[$type]) || $array_sessionKey[$type] == NULL) {
            $this->m_backend_user->backend_login($type);
            $array_sessionKey = $this->session->userdata('backendSessionKey');
            $array_uid = $this->session->userdata('backendUid');
        }
        try {
            $sessionKey = $array_sessionKey[$type];
            $uid = $array_uid[$type];
            $begin_index = 0;

            $contentType = $_GET['contentType'];

            //Message Request
            $getSearchContentRequest = $this->m_content->get_search_content_request($uid, $uuid, $sessionKey, $number, $begin_index, $keywords, $contentType);

            $messageRequest = new zmsg();
            $messageRequest->body_set($getSearchContentRequest);
            $this->mdpClient = new ZmqMDClient($brokerArray[$currentBroker], $verbose);
            $this->mdpClient->connect_to_broker();
            $getSearchContentReply = $this->mdpClient->send("contents", $messageRequest);

            if (!$getSearchContentReply) {
                $currentBroker++;
                if ($currentBroker > count($brokerArray))
                    $currentBroker = 0;
                $this->mdpClient = new ZmqMDClient($brokerArray[$currentBroker], $verbose);
                _jsonout(FALSE, 'Noreply');
            } else {
                $getSearchContent = array();
                $getSearchContent = $this->m_content->get_search_content_reply($getSearchContentReply);

                if (isset($_GET["query"])) {
                    $tags = array();
                    for ($i = 0; $i < count($getSearchContent); $i++) {
                        $tags[$i] = $getSearchContent[$i];
                    }
                } else {
                    $tags = array("tags" => array());
                    for ($i = 0; $i < count($getSearchContent); $i++) {
                        array_push($tags, $getSearchContent[$i]);
                    }
                }

                _typeadhead_jsonout($tags);
            }
        } catch (MongoGridFSException $mge) {
            $array = array(ItemGetReply_ErrorType::FAIL_SYS, $mge->getMessage());
            $jsonEncode = json_encode($array);
            $jsonWriteLog = json_decode($jsonUploadFile, true);
            _jsonout(FALSE, $mge->getMessage()); //Return json array
            log_message('error', $jsonWriteLog);
        } catch (Exception $e) {
            $array = array(ItemGetReply_ErrorType::FAIL, $e->getMessage());
            $jsonEncode = json_encode($array);
            $jsonWriteLog = json_decode($jsonUploadFile, true);
            _jsonout(FALSE, $mge->getMessage()); //Return json array
            log_message('error', $jsonWriteLog);
        }
    }

    /**
     * Function full search of content
     * 
     * @param type $offfset
     * @param type $number
     */
    public function ajax_full_search_content($offfset = 0, $number = 5) {
        $this->_plugins[] = "jquery_ui/js";
        $this->_plugins[] = "jquery_ui/css/Aristo";
        $this->load->library('pagination');

        $offset = $this->input->get('offset', 0);
        $params = array();
        $this->load->library('zmq/ZmqMDClient', $params);

        $mdClient = $this->config->item('mdClient');
        $verbose = $mdClient['verbose'];
        $brokerArray = $mdClient['brokerList'];
        $currentBroker = 0;

        $this->load->library('pb4php');
        $this->load->library('proto/proto');
        $uuid = uniqid();
        $acxLogin = $this->config->item('acxLogin');
        $type = $acxLogin['default'];
        $this->get_backend_session_key($type);

        $keywords = $this->input->post('keyword');
        if ($this->session->userdata('backendSessionKey') == NULL) {
            
        } else {
            try {
                $array_sessionKey = $array_uid = array();
                $array_sessionKey = $this->session->userdata('backendSessionKey');
                $array_uid = $this->session->userdata('backendUid');
                if (!isset($array_sessionKey[$type]) || $array_sessionKey[$type] == NULL) {
                    $this->m_backend_user->backend_login($type);
                    $array_sessionKey = $this->session->userdata('backendSessionKey');
                    $array_uid = $this->session->userdata('backendUid');
                }

                $sessionKey = $array_sessionKey[$type];
                $uid = $array_uid[$type];

                $begin_index = $this->input->post('begin_index');
                if ($begin_index == NULL || $begin_index == '')
                    $begin_index = 0;

                $contentType = $this->input->post('contentType', NULL);

                //Message Request
                $getFullSearchContentRequest = $this->m_content->get_full_search_content_request($uid, $uuid, $sessionKey, $number, $begin_index, $keywords, $contentType);
                $messageRequest = new zmsg();
                $messageRequest->body_set($getFullSearchContentRequest);
                $this->mdpClient = new ZmqMDClient($brokerArray[$currentBroker], $verbose);
                $this->mdpClient->connect_to_broker();
                $getFullSearchContentReply = $this->mdpClient->send("contents", $messageRequest);

                if (!$getFullSearchContentReply) {
                    $currentBroker++;
                    if ($currentBroker > count($brokerArray))
                        $currentBroker = 0;
                    $this->mdpClient = new ZmqMDClient($brokerArray[$currentBroker], $verbose);
                    log_message('error', 'Noreply');  //Ghi log
                    _jsonout(FALSE, 'Noreply');
                } else {
                    $arr_getListContent = $getListContent = $creator = array();
                    $arr_getListContent = $this->m_content->get_full_search_content_reply($getFullSearchContentReply);

                    $getListContent = $arr_getListContent['contentItem'];
                    $creator = $arr_getListContent['creator'];

                    if ($getListContent != NULL) {

                        function cmp($a, $b) {
                            if ($a->update_timestamp() == $b->update_timestamp()) {
                                return 0;
                            }
                            return ($a->update_timestamp() < $b->update_timestamp()) ? 1 : -1;
                        }

                        usort($getListContent, "cmp");
                        $jsonArray = array();

                        $i = 0;
                        foreach ($getListContent as $key => $content) {
                            $jsonArray[$key] = array();
                            if ($content->thumb_picture_uri() != NULL)
                                $content->set_thumb_picture_uri(get_media_url($content->thumb_picture_uri()));
                            array_push($jsonArray[$key], $content->toJson());
                            if ($creator[$i] != NULL) {
                                array_push($jsonArray[$key], $creator[$i]->toJson());
                            }
                            $i++;
                        }


                        $arr_out = array();
                        $arr_out['content'] = $jsonArray;
                        $arr_out['total_items'] = $arr_getListContent['total_items'];

                        _jsonout(TRUE, 'success', json_encode($arr_out));
                    } else {
                        _jsonout(TRUE, 'success', json_encode(array()));
                    }
                }
            } catch (MongoGridFSException $mge) {
                $array = array(ItemGetReply_ErrorType::FAIL_SYS, $mge->getMessage());
                $jsonEncode = json_encode($array);
                $jsonWriteLog = json_decode($jsonUploadFile, true);
                _jsonout(FALSE, $mge->getMessage()); //Return json array
                log_message('error', $jsonWriteLog);
            } catch (Exception $e) {
                $array = array(ItemGetReply_ErrorType::FAIL, $e->getMessage());
                $jsonEncode = json_encode($array);
                $jsonWriteLog = json_decode($jsonUploadFile, true);
                _jsonout(FALSE, $mge->getMessage()); //Return json array
                log_message('error', $jsonWriteLog);
            }
        }
    }

    /***************************************************************************
     * function upload thumb file
     * 
     * ************************************************************************* */

    public function ajax_save_upload_thumb_file() {
        $this->load->helper('number');
        $config = array();
        $tmp_dir = PHOTO_DIR . "/";
        $config['upload_path'] = $tmp_dir;
        $config['allowed_types'] = 'png|jpg|gif|PNG|JPG|GIF';
        $config['max_size'] = '10000';
        $config['max_width'] = '10000';
        $config['max_height'] = '10000';
        $config['file_name'] = time();

        //Set uid & sessionkey
        $acxLogin = $this->config->item('acxLogin');
        $type = $acxLogin['default'];
        $array_sessionKey = $array_uid = array();
        $array_sessionKey = $this->session->userdata('backendSessionKey');
        $array_uid = $this->session->userdata('backendUid');
        if (!isset($array_sessionKey[$type]) || $array_sessionKey[$type] == NULL) {
            $this->m_backend_user->backend_login($type);
            $array_sessionKey = $this->session->userdata('backendSessionKey');
            $array_uid = $this->session->userdata('backendUid');
        }
        $sessionkey = $array_sessionKey[$type];
        $uid = $array_uid[$type];

        $this->load->library('upload', $config);


        if ($this->upload->do_upload()) {
            $data = $this->upload->data();
            $img_path = $tmp_dir . $data['file_name'];
            $photo_id = time();
            // Get photo description
            $photo_desc = $this->input->post('photo_desc');
            // Get photo status, set NULL if it is not posted
            $photo_status = ($this->input->post('photo_status') != "") ? $this->input->post('photo_status') : NULL;
            $media_uri = $this->__save_media_file($img_path, $sessionkey, $uid, $photo_status);

            unlink($img_path);
            if ($media_uri != NULL) {
                // get media uri
                $photo_url = $this->__get_media_url($media_uri);
                if ($photo_id != NULL) {
                    $json_array = array(
                        'media_uri' => $media_uri,
                        'photo_id' => $photo_id,
                        'photo_url' => $photo_url,
                        'album_index' => 0,
                        'photo_desc' => $photo_desc,
                    );
                    $data_out = json_encode($json_array);
                    _jsonout(TRUE, "<h3 class='alert_success'>Upload thành công!<h3/>", $data_out);
                } else {
                    _jsonout(FALSE, "<h3 class='alert_error'> Can not update backend database.<h3/>");
                }
            } else {
                _jsonout(FALSE, "<h3 class='alert_error'>" . $this->upload->display_errors() . "<h3/>");
            }
        } else {
            _jsonout(FALSE, "<h3 class='alert_error'>" . $this->upload->display_errors() . "<h3/>");
        }
    }

    /*     * *************************************************************************
     * 	function Crawl thumb file
     *    
     * ************************************************************************* */

    public function ajax_save_crawl_thumb_picture_file() {
        $this->load->helper('number');
        $photo_url = $this->input->post('photo_url');
        $photo_file = tempnam("/tmp", "acx");

        $handle = fopen($photo_file, "w");
        $acxLogin = $this->config->item('acxLogin');
        $type = $acxLogin['default'];
        $array_sessionKey = $array_uid = array();
        $array_sessionKey = $this->session->userdata('backendSessionKey');
        $array_uid = $this->session->userdata('backendUid');
        if (!isset($array_sessionKey[$type]) || $array_sessionKey[$type] == NULL) {
            $this->m_backend_user->backend_login($type);
            $array_sessionKey = $this->session->userdata('backendSessionKey');
            $array_uid = $this->session->userdata('backendUid');
        }
        $sessionkey = $array_sessionKey[$type];
        $uid = $array_uid[$type];

        if (copy($photo_url, $photo_file)) {
            $photo_status = ($this->input->post('photo_status') != "") ? $this->input->post('photo_status') : NULL;
            $media_uri = $this->__save_media_file($photo_file, $sessionkey, $uid, $photo_status);
            fclose($handle);
            $photo_id = time();

            if ($media_uri != NULL) {
                // get media uri
                $photo_url = $this->__get_media_url($media_uri);
                if ($photo_id != NULL) {
                    $json_array = array(
                        'media_uri' => $media_uri,
                        'photo_id' => $photo_id,
                        'photo_url' => $photo_url,
                        'album_index' => 0,
                    );
                    $data_out = json_encode($json_array);
                    _jsonout(TRUE, "<h3 class='alert_success'>Upload thành công!<h3/>", $data_out);
                } else {
                    _jsonout(FALSE, "<h3 class='alert_error'> Can not update backend database.<h3/>");
                }
            } else {
                _jsonout(FALSE, "Không cập nhật được media server.");
            }
        }
        else
            _jsonout(FALSE, "Không lấy ảnh từ url($photo_url).");
    }

    /*     * *************************************************************************
     * Hàm lấy ảnh từ một URL bài viết và hiển thị danh sách ảnh ra trình duyệt
     * @return fale: Nếu URL không chính xác
     * ************************************************************************* */

    function crawl() {
        $url = prep_url($this->input->post('url'));
        $arrActionImages = array(
            'update' => '<img alt="lên" src="' . base_url() . '/assets/css/_common/images/btn_save.png' . '" width="16px"/>',
            'delete' => '<img alt="lên" src="' . base_url() . '/assets/css/_common/images/btn_delete.png' . '" width="16px"/>',
            'up' => '<img alt="lên" src="' . base_url() . '/assets/css/_common/images/btn_up.png' . '" width="16px"/>',
            'down' => '<img alt="lên" src="' . base_url() . '/assets/css/_common/images/btn_down.png' . '" width="16px"/>',
        );


        if ($url == '' OR filter_var($url, FILTER_VALIDATE_URL) == FALSE) {
            echo "URL không chính xác, bạn vui lòng thử lại";
            return FALSE;
        }

        $html = $this->__getContent($url, null, 'GET', true);
        if ($html == '') {
            echo "<script>alert('Không lấy được nội dung trang web, bạn vui lòng kiểm tra lại hoặc chọn URL khác.')</script>";
            die;
        }

        /**
         * TH1. Các ảnh tuyệt đối (có http:// ở đầu, có .png, .gif, .jpg ở cuối)
         */
        $imageUrlArray = array();
        preg_match_all('!http://[a-z0-9\-\.\/]+\.(?:jpe?g|png|gif)!Ui', $html, $imageUrlArray);

        if (is_array($imageUrlArray)) {
            $imageUrlArray = $imageUrlArray[0];
        }

        $res = preg_match_all('/<img[^>]*>/Ui', $html, $matches);
        foreach ($matches[0] as $img_tag) {
            $pattern = '/src=\"\S*\"/Ui';
            $res = preg_match_all($pattern, $img_tag, $src);
//     		var_dump($src);
        }

        /**
         * TH2. Trường hợp các ảnh có link tương đối nằm trong thẻ <img ...>
         */
        $parse = parse_url($url);
        $baseUrl = $parse['scheme'] . '://' . $parse['host']; // Lấy thông tin domain từ url hiện tại
        libxml_use_internal_errors(true);

        // Xử lý DOM
        $dom = new domDocument;
        $dom->loadHTML($html);
        $dom->preserveWhiteSpace = false;

        // Lấy các phần tử DOM có thẻ là img
        $images = $dom->getElementsByTagName('img');
        foreach ($images as $image) {
            $src = $image->getAttribute('src');
            // Kiểm tra nếu URL đã lấy trong TH1 rồi thì bỏ qua
            if (in_array($src, $imageUrlArray))
                continue;

            // Kiểm tra ảnh nếu không có http thì thêm vào
            $fullUrl = (strpos($src, "http://") !== FALSE OR strpos($src, "https://") !== FALSE) ? $src : $baseUrl . $src;
            array_push($imageUrlArray, $fullUrl);
        }
        _jsonout(TRUE, "Successfully crawl the url.", json_encode($imageUrlArray));
    }

    /**
     * Hàm xử lý AJAX gọi lên để lưu file
     *
     * @param intege $item_id
     * @return intege
     */
    public function save_crawler_file() {
        $this->load->helper('number');
        $file = $this->input->post('file');
        $media_server = $this->config->item('media_server');
        $url = $media_server['post_url'];
        $photo_file = tempnam("/tmp", "acx");

        if (copy($file, $photo_file)) {
            $filezie = @filesize($photo_file);

            if ($photo_file != '') {
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_HEADER, 0);
                curl_setopt($ch, CURLOPT_VERBOSE, 0);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_POST, true);
                $post = array(
                    "file" => "@" . $photo_file . ';type=' . mime_content_type($photo_file),
                );
                curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
                $response = curl_exec($ch);
                _jsonout(TRUE, $response, "<div style='color:green'>Crawl ảnh thành công!</div>");
            }
        }
        else
            _jsonout(FALSE, $response, "Không crawl được ảnh này!");
        fclose($photo_file);
    }

    /**
     * 	ajax_save_crawl_file
     *
     * 	Crawl and save link
     */
    public function ajax_save_crawl_file() {
        $this->load->helper('number');

        $photo_url = $this->input->post('photo_url', '');
        $photo_desc = $this->input->post('photo_desc', '');
        $photo_index = $this->input->post('photo_index', '');
        $type = $this->input->post('creator', '');

        $photo_id = '';
        $media_uri = '';
        $media_url = '';
        $json_array = array();

        //Set uid & sessionkey
        if ($type == '') {
            $acxLogin = $this->config->item('acxLogin');
            $type = $acxLogin['default'];
        }
        $array_sessionKey = $array_uid = array();
        $array_sessionKey = $this->session->userdata('backendSessionKey');
        $array_uid = $this->session->userdata('backendUid');
        if (!isset($array_sessionKey[$type]) || $array_sessionKey[$type] == NULL) {
            $this->m_backend_user->backend_login($type);
            $array_sessionKey = $this->session->userdata('backendSessionKey');
            $array_uid = $this->session->userdata('backendUid');
        }
        $sessionkey = $array_sessionKey[$type];
        $uid = $array_uid[$type];
        $item_id = $this->input->post('item_id', NULL); 
        if ($item_id != NULL) {
            $photo_file = tempnam("/tmp", "acx");
            $handle = fopen($photo_file, "w");            
            if (copy($photo_url, $photo_file)) {
                $photo_status = ($this->input->post('photo_status') != "") ? $this->input->post('photo_status') : NULL;                                
                $media_uri = $this->__save_media_file($photo_file, $sessionkey, $uid, $photo_status);
                $media_url = $this->__get_media_url($media_uri);
            } else {             
                $media_uri = NULL;
                $media_url = NULL;
            }            
            fclose($handle);            

            $photo_id = NULL;
            if ($media_url != NULL) {
                $contentType = $this->input->post('contentType', NULL);
                $photo_id = $this->createPhotos($item_id, $contentType, $photo_desc, $media_uri, $photo_index, $type);
            }

            if ($photo_id != NULL) {
                array_push($json_array, array(
                    'media_uri' => $media_uri,
                    'photo_id' => $photo_id,
                    'photo_url' => $photo_url,
                    'item_id' => $item_id,
                    'album_index' => 0,
                    'photo_desc' => $photo_desc
                ));
                $data_out = json_encode($json_array);
                _jsonout(TRUE, "Upload thành công!", $data_out);
            } else {
                _jsonout(FALSE, "Không cập nhật được hệ thống backend.");
            }
        }
    }

    /*
     * Create Photo
     */

    function createPhotos($item_id, $contentType = NULL, $description = NULL, $photo_uri = NULL, $album_photo_index = NULL, $creator = NULL, $photo_source = NULL, $photo_size = NULL) {       
        $params = array();
        $this->load->library('zmq/ZmqMDClient', $params);

        $mdClient = $this->config->item('mdClient');
        $verbose = $mdClient['verbose'];
        $brokerArray = $mdClient['brokerList'];
        $currentBroker = 0;

        $this->load->library('pb4php');
        $this->load->library('proto/proto');
        $uuid = uniqid();

        try {
            $type = $creator;
            if ($type == '') {
                $acxLogin = $this->config->item('acxLogin');
                $type = $acxLogin['default'];
            }

            $array_sessionKey = $array_uid = array();
            $array_sessionKey = $this->session->userdata('backendSessionKey');
            $array_uid = $this->session->userdata('backendUid');
            if (!isset($array_sessionKey[$type]) || $array_sessionKey[$type] == NULL) {
                $this->m_backend_user->backend_login($type);
                $array_sessionKey = $this->session->userdata('backendSessionKey');
                $array_uid = $this->session->userdata('backendUid');
            }
            $sessionKey = $array_sessionKey[$type];
            $uid = $array_uid[$type];

            //Message request
            $createPhotoRequestMessage = $this->m_content->get_create_photos_request($uid, $uuid, $sessionKey, $item_id, $contentType, $description, $photo_uri, $album_photo_index, $photo_source, $photo_size);
          
            $messageRequest = new zmsg();
            $messageRequest->body_set($createPhotoRequestMessage);

            $this->mdpClient = new ZmqMDClient($brokerArray[$currentBroker], $verbose);
            $this->mdpClient->connect_to_broker();
            $createPhotoMessageReply = $this->mdpClient->send("contents", $messageRequest);

            if (!$createPhotoMessageReply) {
                $currentBroker++;
                if ($currentBroker > count($brokerArray))
                    $currentBroker = 0;
                $this->mdpClient = new ZmqMDClient($brokerArray[$currentBroker], $verbose);
                log_message('error', 'Noreply');  //Ghi log
                _jsonout(FALSE, 'Noreply');
            } else {
                $itemCRUDReply = $this->m_content->get_message_reply($createPhotoMessageReply);
                if ($itemCRUDReply->error_no() == ItemCRUDReply_ErrorNo::SUCCESS) {
                    $data['error'] = $itemCRUDReply->error_msg();
                    log_message('error', $itemCRUDReply->error_msg()); //Ghi log trường hợp không thành công
                    return $itemCRUDReply->item_id(0);
                } else {
                    return NULL;
                }
            }
        } catch (Exception $e) {
            log_message('error', $e->getMessage());
            return NULL;
        }
    }

    /*     * *************************************************************************
     * funcion update photo
     * 
     * ************************************************************************* */

    public function ajax_update_photo() {
        try {
            $photo_id = $this->input->post('id');
            //TODO: add code to change photo uri
            $photo_uri = $this->input->post('uri');
            $description = $this->input->post('desc', NULL);
            $item_id = $this->input->post('item_id', NULL);
            $album_photo_index = $this->input->post('album_photo_index', NULL);
            if ($photo_id != NULL || $album_id == NULL) {
                // get backend uid session key
                $type = $this->input->post('creator');
                if ($type == '') {
                    $acxLogin = $this->config->item('acxLogin');
                    $type = $acxLogin['default'];
                }

                $array_sessionKey = $array_uid = array();
                $array_sessionKey = $this->session->userdata('backendSessionKey');
                $array_uid = $this->session->userdata('backendUid');
                if (!isset($array_sessionKey[$type]) || $array_sessionKey[$type] == NULL) {
                    $this->m_backend_user->backend_login($type);
                    $array_sessionKey = $this->session->userdata('backendSessionKey');
                    $array_uid = $this->session->userdata('backendUid');
                }
                $session_key = $array_sessionKey[$type];
                $uid = $array_uid[$type];

                // update backend & return data
                $contentType = $this->input->post('contentType', NULL);
                if ($this->m_content->update_photo($uid, $session_key, $photo_id, $item_id, $contentType, $description, $photo_uri, NULL, NULL, $album_photo_index)) {
                    _jsonout(TRUE, "Cập nhật thành công!");
                } else {
                    _jsonout(FALSE, "Không cập nhật được hệ thống backend.");
                }
            } else {
                _jsonout(FALSE, "Không xác định được id của photo.<h3/>");
            }
        } catch (Exception $e) {
            log_message("error", "Got an exception when delete photo. " . $e->getMessage());
            _jsonout(FALSE, "Exception xảy ra khi xóa photo");
        }
    }

//    public function ajax_update_photo() {       
//        try {
//            $photo_id = $this->input->post('id');
//            //TODO: add code to change photo uri
//            $photo_uri = $this->input->post('uri');
//            $description = $this->input->post('desc', NULL);
//            $item_id = $this->input->post('item_id', NULL);
//            $album_photo_index = $this->input->post('album_photo_index', NULL);
//            if ($photo_id != NULL || $album_id == NULL) {
//                // get backend uid session key
//                $type = $this->input->post('creator');
//                $array_sessionKey = $array_uid = array();
//                $array_sessionKey = $this->session->userdata('backendSessionKey');
//                $array_uid = $this->session->userdata('backendUid');
//                if (!isset($array_sessionKey[$type]) || $array_sessionKey[$type] == NULL) {
//                    $this->m_backend_user->backend_login($type);
//                    $array_sessionKey = $this->session->userdata('backendSessionKey');
//                    $array_uid = $this->session->userdata('backendUid');
//                }
//                $session_key = $array_sessionKey[$type];
//                $uid = $array_uid[$type];
//                              
//                // update backend & return data
//                $contentType = $this->input->post('contentType', NULL);
//                if ($this->m_content->update_photo($uid, $session_key, $photo_id, $item_id, $contentType, $description, $photo_uri, NULL, NULL, $album_photo_index)) {
//                    _jsonout(TRUE, "Cập nhật thành công!");
//                } else {
//                    _jsonout(FALSE, "Không cập nhật được hệ thống backend.");
//                }
//            } else {
//                _jsonout(FALSE, "Không xác định được id của photo.<h3/>");
//            }
//        } catch (Exception $e) {
//            log_message("error", "Got an exception when delete photo. " . $e->getMessage());
//            _jsonout(FALSE, "Exception xảy ra khi xóa photo");
//        }
//    }


    /*     * *************************************************************************
     * function Delele photo
     * 
     * ************************************************************************* */
    public function ajax_delete_photo() {
        $photo_id = $this->input->post('photo_id');
        $item_id = $this->input->post('item_id');
        try {
            if ($photo_id != NULL) {
                // delete file from media server
                $photo_status = "DELETE";
                $type = $this->input->post('creator');
                if ($type == '') {
                    $acxLogin = $this->config->item('acxLogin');
                    $type = $acxLogin['default'];
                }               

                $array_sessionKey = $array_uid = array();
                $array_sessionKey = $this->session->userdata('backendSessionKey');
                $array_uid = $this->session->userdata('backendUid');
                if (!isset($array_sessionKey[$type]) || $array_sessionKey[$type] == NULL) {
                    $this->m_backend_user->backend_login($type);
                    $array_sessionKey = $this->session->userdata('backendSessionKey');
                    $array_uid = $this->session->userdata('backendUid');
                }
                $session_key = $array_sessionKey[$type];
                $uid = $array_uid[$type];

                if ($this->__update_media_file($photo_id, $photo_status)) {
                    // update backend & return data
                    $contentType = $this->input->post('contentType', NULL);
                    if ($this->m_content->delete_photo($uid, $session_key, $photo_id, $item_id, $contentType)) {
                        _jsonout(TRUE, "Xóa thành công photo(id:$photo_id) !");
                    } else {
                        _jsonout(FALSE, "Không cập nhật được hệ thống backend.");
                    }
                } else {
                    _jsonout(FALSE, "Không cập nhật được media server.");
                }
            } else {
                _jsonout(FALSE, "Không xác định được id của photo.<h3/>");
            }
        } catch (Exception $e) {
            log_message("error", "Got an exception when delete photo. " . $e->getMessage());
            _jsonout(FALSE, "Exception xảy ra khi xóa photo.");
        }
    }

}